package com.pencilisland.pay.app.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.pencilisland.pay.api.bean.constant.OrderConstant;
import com.pencilisland.pay.api.bean.constant.WxpayConstant;
import com.pencilisland.pay.api.bean.mp.core.WxpayNotifyREQ;
import com.pencilisland.pay.api.bean.mp.core.WxpayNotifyRES;
import com.pencilisland.pay.api.bean.wxpay.WxpayCallbackNotifyReq;
import com.pencilisland.pay.api.bean.wxpay.WxpayCallbackNotifyResp;
import com.pencilisland.pay.api.entity.TradeOrderEntity;
import com.pencilisland.pay.api.repository.TradeOrderRepository;
import com.pencilisland.pay.api.util.JaxbUtil;
import com.pencilisland.pay.app.service.AppWxpayService;
import com.pencilisland.pay.app.service.RestService;

@Component
public class AppWxpayServiceImpl implements AppWxpayService {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	RestService restService;
	
	@Autowired
	TradeOrderRepository tradeOrderRepo;

	@Override
	public WxpayCallbackNotifyResp callbackNotify(String requestXml) {
		WxpayCallbackNotifyResp resp = new WxpayCallbackNotifyResp();
		if (StringUtils.isEmpty(requestXml)) {
			resp.setReturnCode(WxpayConstant.FAIL);
			resp.setReturnMsg("接收报文为空");
			return resp;
		}

		WxpayCallbackNotifyReq req = JaxbUtil.converyToJavaBean(requestXml, WxpayCallbackNotifyReq.class);
		
		if (WxpayConstant.SUCCESS.equals(req.getReturnCode())) {
			TradeOrderEntity tradeOrder = tradeOrderRepo.findOne(req.getOutTradeNo());
			if(tradeOrder!=null&&!StringUtils.isEmpty(tradeOrder.getTransactionId())){
				log.info("订单【{}】已经处理，不再重复处理",req.getOutTradeNo());
				resp.setReturnCode(WxpayConstant.SUCCESS);
				return resp;
			}
			
			//更新订单信息
			if(tradeOrder==null){
				resp.setReturnCode(WxpayConstant.FAIL);
				resp.setReturnMsg("订单记录不存在");
				return resp;
			}
			
			tradeOrder.setTransactionId(req.getTransactionId());
			tradeOrder.setFinishTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
			
			if (WxpayConstant.SUCCESS.equals(req.getResultCode())){
				tradeOrder.setPayStatus(OrderConstant.PAY_STATUS_1);
				tradeOrder.setStatus(OrderConstant.STATUS_1);
			}else if(WxpayConstant.FAIL.equals(req.getResultCode())){
				tradeOrder.setPayStatus(OrderConstant.PAY_STATUS_2);
				tradeOrder.setStatus(OrderConstant.STATUS_4);
				
			}
			
			tradeOrderRepo.save(tradeOrder);
			
			
			WxpayNotifyREQ notifyReq = new WxpayNotifyREQ();
			notifyReq.setOrderNo(tradeOrder.getOrderNo());
			notifyReq.setResult(req.getResultCode());
			notifyReq.setRenewStock("1");
			
			restService.sendToCoreMP("wxpayNotify", notifyReq, WxpayNotifyRES.class);
		}

		resp.setReturnCode(WxpayConstant.SUCCESS);
		return resp;
	}

}
